var mongoose = require('./mongodb.js');
var Schema = mongoose.Schema
var when = require('when');
var User = require('./user.js');
var addressSchema = new Schema({
    _id: Schema.Types.ObjectId,
    address: String,
    location: String,
    lon: Number,
    lat: Number,
    islocation: Boolean
}, {collection: 'address'});
var Address = mongoose.model('Address', addressSchema);

// commit schema
var commentSchema = new Schema({
    _id: Schema.Types.ObjectId,
    author: Schema.Types.ObjectId,
    content: String,
    date: Date,
    parent: [{type: Schema.Types.ObjectId, ref: 'Comment'}]
}, {collection: 'comment'});

commentSchema.statics = {
    /*
     * 插入数据
     * date:发布时间
     * content:发布内容
     * author:作者
     * */
    insertComment: function (date, content, author, callBack) {
        console.log(mongoose.Types.ObjectId());
        var comment = new Comment({
                '_id': mongoose.Types.ObjectId(),
                'author': author,
                'content': content,
                'date': new Date(),
                'parent': null
        });
        comment.save(callBack);
    },
    /*
     * 插入评论的评论
     * date: 发布时间
     * content:发布内容
     * author:作者
     * id:被评论的id
     * activityID: 活动id
     * */
    insertCommentForID: function (date, content, author, id, activity, callBack) {
        var parent = new Array();
        Comment.find({'_id': id}).exec(function (err, doc) {
            if (!err) {
                parent.concat(doc[0].parent);
            }
        });
        parent.push(id);
        Comment.save({
            '_id': Schema.Types.ObjectId(),
            'author': author,
            'content': content,
            'date': new Date(),
            'parent': parent
        });
    },
    findCommentWithIDS: function (ids, callBack) {
        Comment
            .find({'_id': {$in: ids}})
            .populate('parent')
            .exec(function (err, doc) {
                for (var i = 0; i < doc.length; i++) {

                }
            });
    }

}

var Comment = mongoose.model('Comment', commentSchema);

var activitySchema = new Schema({
    _id: Schema.Types.ObjectId,// id
    title: String,// 标题
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },// 作者id
    date: Date, //  发表时间
    content: String, // 内容
    images: Array, // 图片id,
    comment: [{type: Schema.Types.ObjectId, ref: 'Comment'}],// 评论id
    collected: Array,
    address: {
        type: Schema.Types.ObjectId,
        ref: 'Address'
    }, // 活动地址id
    people: Number, //报名人数
    money: String,   // 报名费
    time: String,     // 活动时间
    city: Number
}, {'collection': 'activity'});

activitySchema.statics = {
    /*
     * 查找比id对应的活动时间更早的活动，
     * id: 活动id
     * count: 数目
     * */
    findByIDWithLimit: function (id, count, callBack) {
        return this.model('activity')
            .find({})
            .sort({'_id': -1})
            .where('_id')
            .lt(id)
            .limit(count)
            .populate({path: 'author', select: 'headImage nickName -_id'})
            .populate({path: 'address', select: 'address'})
            .exec(callBack);
    },
    /*
    * 查找更晚的活动
    * id
    * count 数量
    * */
    findByIDWithGte:function (id, count, callBack) {
        return this.model('activity')
            .find({})
            .sort({'_id': -1})
            .where('_id')
            .gt(id)
            .limit(count)
            .populate({path: 'author', select: 'headImage nickName -_id'})
            .populate({path: 'address', select: 'address'})
            .exec(callBack);
    },
    /*查找所动列表
     * count:列表限制
     * */
    findNewWithLimit: function (count, callBack) {
        return this.model('activity')
            .find({})
            .sort({'_id': 1})
            .limit(count)
            .populate({path: 'author', select: 'headImage nickName -_id'})
            .populate({path: 'address', select: 'address'})
            .exec(callBack);
    },
    /*
     * 根据活动id查找对应的回复
     * id 活动id
     * count 回复的数量
     * start 开始的回复id
     * callback 回调函数
     * */
    findCommentByIDWithLimit: function (id, count, start, callBack) {    //根据活动id获取count个回复
        if (start) {
            return this.model('activity')
                .aggregate([{$match: {_id: mongoose.Types.ObjectId(id)}}
                    , {$unwind: '$comment'}
                    , {$match: {comment: {$lt: mongoose.Types.ObjectId(start)}}}
                    , {$project: {comment: 1, _id: 0}}
                    , {$limit: parseInt(count)}])
                .exec(function (err, result) {
                    if (!err) {
                        Activity.findCommitByIDs(result, callBack);
                    } else {
                        callBack(err, null);
                    }
                });
        } else {
            return this.model('activity')
                .aggregate([{$match: {_id: mongoose.Types.ObjectId(id)}}
                    , {$unwind: '$comment'}
                    , {$project: {comment: 1, _id: 0}}
                    , {$limit: parseInt(count)}])
                .exec(function (err, result) {
                    if (!err) {
                        console.log(result);
                        Activity.findCommentByIDs(result, callBack);
                    } else {
                        callBack(err, null);
                    }
                });
        }
    },

    findCommentByIDs: function (ids, callBack) {
        var arr = new Array();
        for (var item in ids) {
            arr.push(ids[item].comment);
        }
        console.log(arr);
        return Comment
            .find({'_id': {$in: arr}})
            .populate('parent')
            .exec(callBack);
    },

    /*
     * 给activity插入评论
     * id :acitvityid
     * date: 评论时间
     * author: 评论作者
     * content:评论内容
     * callBack:回调函数
     * */
    insertCommentByID: function (id, date, author, content, callBack) {
        Comment.insertComment(date, content, author, function (err, doc) {   //在comments表中插入comment并返回id
            if (err) {
                callBack(err, doc);
            } else {
                Activity.update({'_id': id}, {$addToSet: {comment: doc._id}}, function (err, doc) {// 更新activity表中的comments数组
                        if (err) {
                            callBack(err, doc)
                        } else {
                            User.update({'_id': author}, {$addToSet: {comment: doc._id}}, function (error, doc) {//更新user表中author的comment数组
                                if (err) {
                                    callBack(err, doc);
                                } else {
                                    callBack(err, doc);
                                }
                            })
                        }
                    });
            }
        })
    }
};
var Activity = mongoose.model('activity', activitySchema);

module.exports = {
    activity: Activity,
    address: Address,
    comment: Comment
};
